//
//  ANWebService+User.m
//  Ants
//
//  Created by ZHM on 16/4/24.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANWebService+User.h"
#import "UIImageView+WebCache.h"

@implementation ANWebService (User)

- (BOOL)isLoggedIn {
    BmobUser *currentUser = [BmobUser getCurrentUser];
    return currentUser != nil;
}

- (ANBmobUser *)currentUser {
    if (self.isLoggedIn) {
        return self.user;
    }
    return nil;
}
- (void)fetchUserWithBmobCompletion:(void(^)(ANBmobUser *user, NSError *error))completion {
    ANBmobUser *user = [[ANBmobUser alloc] initFromBmobObject:[BmobUser getCurrentUser]];
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
    [bquery getObjectInBackgroundWithId:[BmobUser getCurrentUser].objectId block:^(BmobObject *object, NSError *error) {
        if (!error) {
            //将返回的用户信息转换成ANBmobUser 返回
            user.nickName = [object objectForKey:@"nickName"];
            user.tel = [object objectForKey:@"tel"];
            user.iconImage = [object objectForKey:@"iconImage"];
            ANLog(@"A:user. = %@",user.nickName);
            self.user = user;
            ANLog(@"%p=>",self.user);
            ANLog(@"获取用户数据并返回");

            BLOCK_SAFE_ASY_RUN_MainQueue(completion, user, nil);
            
        } else {
            ANLog(@"获取用户数据出错:%@,",error);
            [SVProgressHUD showSuccessWithStatus:@"网络连接失败!"];
            //获取表里第一条数据
            ANBDUser *userBD = [ANBDUser MR_findFirst];
            userBD.nickname = user.nickName;
            userBD.tel = user.tel;
            userBD.iconImage = user.iconImage;
            ANLog(@"本地数据::::::%@",userBD.nickname);
            self.user = user;
            [self showEerorView:error];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, user, error);
        }
    }];
}
//本地保证用户信息
- (void)fetchUserBasicInfoWithCompletion:(void(^)(ANBDUser *user, NSError *error))completion {
    ANBmobUser *mlUser = self.currentUser;
    NSString *nickName = mlUser.nickName;
    if ([self isLoggedIn]) {
        [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
            ANBDUser *user = [ANBDUser MR_findFirstOrCreateByAttribute:@"nickname" withValue:nickName inContext:localContext];
            user.nickname = nickName;
            user.tel = mlUser.tel;
            user.iconImage = mlUser.iconImage;
            ANLog(@"nickName%@,tel:%@",nickName,mlUser.tel);
            ANLog(@"用户信息本地保存成功");
            
        } completion:^(BOOL contextDidSave, NSError *error) {
            if (error) {
                DDLogError(@"magical record - save user info error:%@", error.localizedDescription);
            }
            ANBDUser *user = [ANBDUser MR_findFirst];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, user, error);
        }];
        
    } else {
        BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, nil);
    }
}

/**
 * 账号 注册
 */

- (void)registeredWithName:(NSString *)name passWord:(NSString *)passWord completion:(void(^)(ANBmobUser *user,BOOL succeeded,NSError *error))completion {
    //ANBmobUser *user = [[ANBmobUser alloc] initFromBmobObject:[BmobUser getCurrentUser]];
    BmobUser *bmobUser = [[BmobUser alloc] init];
    ANBmobUser *user = [[ANBmobUser alloc] initFromBmobObject:bmobUser];
    user.username = name;
    user.password = passWord;
    [user setObject:name forKey:@"nickName"];
    [user signUpInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,user,YES,nil);
        } else {
            [self showEerorView:error];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, NO, error);
        }
    }];
}
/**
 * 账号 登录
 */
- (void)loginWithAccount:(NSString *)account passWord:(NSString *)passWord completion:(void(^)(BmobUser *user, BOOL succeeded, NSError *error))completion {
    //用户名登录
//    [BmobUser loginWithUsernameInBackground:name password:passWord block:^(BmobUser *user, NSError *error) {
//        if (!error) {
//            BLOCK_SAFE_ASY_RUN_MainQueue(completion,user,YES,nil);
//        } else {
//            [self showEerorView:error];
//            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, NO, error);
//        }
//    }];
    //用户名/手机号/邮箱-都可以登录
    [BmobUser loginInbackgroundWithAccount:account andPassword:passWord block:^(BmobUser *user, NSError *error) {
        if (!error) {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,user,YES,nil);
        } else {
            [self showEerorView:error];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, NO, error);
        }
    }];
}



- (void)updateNickName:(NSString *)nickName completion:(void(^)(BOOL succeeded, NSError *error))completion {
    ANBmobUser *user = [self currentUser];
    [user setObject:nickName forKey:@"nickName"];
    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            ANLog(@"-------------已经更新");
        }
        if (!error) {
            ANLog(@"修改成功啦");
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,YES,nil);
        } else {
            ANLog(@"修改失败啦");
            [self showEerorView:error];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,NO, error);
        }
    }];
}

- (void)updatePhoneNumber:(NSString *)phoneNumber completion:(void(^)(BOOL succeeded, NSError *error))completion {
    ANBmobUser *user = [self currentUser];
    ANLog(@"%@--%@",user.tel,self.user.tel);
    [user setObject:phoneNumber forKey:@"tel"];
    [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (!error) {
            ANLog(@"修改成功啦");
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,YES,nil);
        } else {
            ANLog(@"修改失败啦");
            [self showEerorView:error];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,NO, error);
        }
    }];
}
/**
 * 更新头像
 */
- (void)updatePhoto:(UIImage *)image completion:(void(^)(NSString *filePath, BOOL succeeded, NSError *error))completion {
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    
    BmobFile *file = [[BmobFile alloc] initWithFileName:[NSString stringWithFormat:@"%@Photo.jpg",self.user.username] withFileData:imageData];

    [file saveInBackground:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful && !error) {
            ANLog(@"file.url:%@",file.url);
            //本地存储
            ANBDUser *userBD = [ANBDUser MR_findFirstInContext:self.defaultContext];
            ANLog(@"准备删除:%@",userBD.iconImage);
            [self removeFilesWithArray:@[userBD.iconImage] completion:^(NSArray *filePaths, BOOL succeeded, NSError *error) {
                if (!error) {
                    ANLog(@"删除文件成功:%ld",(unsigned long)filePaths.count);
                } else {
                    ANLog(@"删除文件失败:%@",error);
                }
            }];
            userBD.iconImage = file.url;
            [self.defaultContext MR_saveToPersistentStoreAndWait];
            //网络存储
            ANBmobUser *userBM = [sharedWebService currentUser];
            //删除弃用Web图片
            [userBM setObject:file.url forKey:@"iconImage"];
            [userBM updateInBackgroundWithResultBlock:nil];
            
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,file.url,YES,nil);
        } else {
            [self showEerorView:error];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,nil,NO,error);
        }
    }];
}
- (void)showEerorView:(NSError *)error {
    if (error.code == 20002) {
        [SVProgressHUD showSuccessWithStatus:@"网络连接失败!"];
    }else {
        [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"出错啦:%ld",(long)error.code]];
    }
}
- (void)syncUserIconWithBmobWithCompletion:(void(^)(BOOL succeeded, NSError *error))completion {

    //NSString *webPath = [self currentUser]
    
    
}
- (void)logout {
    [BmobUser logout];
}

@end
